
--[[

--]]
----local logger=logger;
local DispatchServiceImpl = Class("com.ea.ctrl.DispatchServiceImpl")

local util = require "com.ea.util.utils";
local cjson = require "cjson";
local http = require("resty.http") ;
local ngx_encode_args = ngx.encode_args


function DispatchServiceImpl:init()
end;
function DispatchServiceImpl:doService(request, response,req_uri)

    local last_req_args = util:get_req_args_all();
    local httpc = http:new()
    last_req_args["userid"]="";--禁止APP等传递UserID过来。    
    local v_userInfo = request:getAttribute("userinfo");
    
    local m, err = ngx.re.match(req_uri, "^/newseller/");    
    if m~=nil then 
         last_req_args["shopid"]="";--微店用户需要将请求中的shopId屏蔽掉。            
    end
    
    local m, err = ngx.re.match(req_uri, "^/ysnewbuyer/");
    if m~=nil then 
         last_req_args["shopid"]="";--云商资源需要将请求中的shopId屏蔽掉。   
             
    end
    
    local uriSplitPath = util:split(req_uri,"/");
    
    local urlMapKey=uriSplitPath[1].."/"..uriSplitPath[2].."/"..uriSplitPath[3].."/";
    
    local appConfig=luastar_context.loadJsonConfig("config");
    local serverPath =nil;
    for key,v in pairs(appConfig.url_map) do
      if key==urlMapKey then
         serverPath=v;
         break;
       end
    end
    
  if not serverPath then
      response:responseJson(cjson.encode({state=4020002,msg="系统繁忙，请稍后再试",data=nil}));
      --response.finish();
      ngx.log(ngx.ERR,logger.formatMsg("cannot parse the corrent server second path."));
      --util:output_plain(result);
      return;
  end;
  
  ngx.log(ngx.INFO,logger.formatMsg("=================================== find server :"..serverPath))
     


  local resultServerRoot; 
  local m, err = ngx.re.match(serverPath, "(.*)/");
  if m then
    resultServerRoot = m[0];
  else
    response:responseJson(cjson.encode({state=4020002,msg="系统繁忙，请稍后再试",data=nil}));
    ngx.log(ngx.ERR,logger.formatMsg("cannot parse the corrent server  path."));
    --util:output_plain(result);
    return;
  end
  
  local namespaceFirst = ngx.re.gsub(serverPath,resultServerRoot,"");
  if not namespaceFirst then
    response:responseJson(cjson.encode({state=4020002,msg="系统繁忙，请稍后再试",data=nil}));
    ngx.log(ngx.ERR,logger.formatMsg("cannot parse the corrent server second path."));
    --util:output_plain(result);
    return;
  end;
  
  local resultUrlPath = "/"..namespaceFirst;
  local _len=#uriSplitPath;
  for i=4,_len do
    resultUrlPath =resultUrlPath.."/"..uriSplitPath[i];
  end;
  --resultUrlPath =resultUrlPath..".do";
  
  ngx.log(ngx.INFO,logger.formatMsg(string.format("==================== call child server:server=%s uri=%s",resultServerRoot,resultUrlPath)));
  
  --- set t_id, userId,userPhone etc.------------------------
  local tId =  util:get_req_param("tid",last_req_args)
  if not tId then
   tId = util:generate_tid();
   last_req_args["t_id"]=tId;
   last_req_args["tid"]=tId;
  end
  --- shopid为接入层保留字，如果当前登录用户是微店用户时，当redis会话中存在该shopId，
  --- 则向接入层后端系统传shopid,当redis会话中不存在shopid则向后端系统传shopid为空白。
 if v_userInfo~=nil then
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("userType=%s  shopId=%s",v_userInfo:getUserType(),v_userInfo:getShopId()))) end
      if v_userInfo:getUserType()==2 then
      if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("in usertype=2,shopName=%s",v_userInfo:getShopName()))) end
      if  _.isEmpty(v_userInfo:getShopId())==false then
          last_req_args["shopid"]=v_userInfo:getShopId();
      else
          last_req_args["shopid"]="";
      end
      if  _.isEmpty(v_userInfo:getShopName())==false then
         last_req_args["acshopname"]=v_userInfo:getShopName();
      else
         last_req_args["acshopname"] ="  "
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("set shopName is nil")) end
      end
      if  _.isEmpty(v_userInfo:getCityId())==false then
         last_req_args["cityid"]=v_userInfo:getCityId();
      else
         last_req_args["cityid"] ="  "
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("set cityid is nil")) end
      end  
     
    end;
    
    last_req_args["userid"]=v_userInfo:getUserId();
    last_req_args["phone"]=v_userInfo:getPhone();
    last_req_args["nickname"]=v_userInfo:getNickName();  
      
  end
  
  ---以参数的形式向后台提交appname
  last_req_args["appname"]=request:get_header("appname","");
  
  if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("params :",cjson.encode(last_req_args))); end
  --- setting end...  --------------------------------------------------
  local mybody = ngx_encode_args(last_req_args);
  ngx.log(ngx.ERR,logger.formatMsg(string.format("req body is %s",mybody)));
  local resp,err = httpc:request_uri(resultServerRoot,{
    method = "POST",
    path = resultUrlPath,
    body=mybody,
    headers={["X-Real-IP"]=ngx.var.remote_addr,["X-Forwarded-For"]=ngx.var.proxy_add_x_forwarded_for,["appname"]=request:get_header("appname",""),["content_type"] = "application/x-www-form-urlencoded"}
  })
  if not resp then
    ngx.log(ngx.ERR,logger.formatMsg(string.format("访问后台服务器 出错,%s %s",resultServerRoot,resultUrlPath)));
  end
  return resp,err;
      
     
    
end

return  DispatchServiceImpl;
